import { app, BrowserWindow, Menu, ipcMain, Event, BrowserWindowConstructorOptions } from 'electron'
import path from 'path'
import debug from './debug'

// 开启 debug
debug()

let mainWindow: BrowserWindow | null = null
let isDev: boolean = process.env.NODE_ENV === 'development'
const winURL = isDev ? `http://localhost:9080` : `file://${__dirname}/index.html`
const appName = 'Electron DbClinet'

if (process.mas) {
  app.setName(appName)
}

function createWindow () {
  Menu.setApplicationMenu(null)

  const windowOptions: BrowserWindowConstructorOptions = {
    height: 400,
    width: 600,
    useContentSize: true,
    show: false,
    resizable: false,
    center: true,
    title: app.getName()
  }

  if (process.platform === 'linux') {
    windowOptions.icon = path.join(__dirname, '/assets/app-icon/png/512.png')
  }

  /**
   * Initial window options
   */
  mainWindow = new BrowserWindow(windowOptions)

  interface Extentions {
    [ key: string ]: any // Add index signature
  }

  // mainWindow.maximize()
  mainWindow.loadURL(winURL)

  mainWindow.on('closed', () => {
    mainWindow = null
  })

  mainWindow.once('ready-to-show', () => {
    if (mainWindow !== null) {
      mainWindow.show()
    }
  })
}

app.on('ready', createWindow)

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', () => {
  if (mainWindow === null) {
    createWindow()
  }
})

ipcMain.on('bootstrap-stage', (event: Event, stage: string) => {
  if (stage === 'finished') {
    if (mainWindow) {
      mainWindow.setResizable(true)
      mainWindow.maximize()
    }
  }
  event.returnValue = 'success'
})
